package com.ws.utils;

import com.ws.dao.SssfmNxYthServerDao;
import com.ws.entity.SssfmNxYthServer;
import com.ws.response.NxYthHttpResponse;
import com.ws.utils.safeUtil.TranSM4Utils;
import com.ws.utils.safeUtil.Util;
import com.ws.utils.sm.SM2Utils;
//import com.ws.utils.sm.SM4Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * @ClassName InitKeyHttpUtil
 * @Description InitKeyHttpUtil
 * @Author gxx
 * @Date 2020/12/1 9:32
 * @Version 1.0
 */
@Service
public class InitKeyHttpUtil {


    @Autowired
    private SssfmNxYthServerDao sssfmNxYthServerDao;

    private static Map<String,SssfmNxYthServer> services= new HashMap<>();

    /**
     * 业务系统向交换平台备案公钥
     */
    public static NxYthHttpResponse registerSysPubKey(SssfmNxYthServer sssfmNxYthServer) {
        Map map = SM2Utils.generateKeyPair();
        Map headers = getHeader(sssfmNxYthServer, false);
        StringBuilder postJson = new StringBuilder();
        postJson.append("{\"SE_sysPubKey\":\"");
        postJson.append(map.get(SM2Utils.PUBLIC_KEY));
        postJson.append("\"}");
        String s = NXHttpUtil.doPost(sssfmNxYthServer.getUrl(), headers, postJson.toString(), sssfmNxYthServer.getUrlTimeout());
        System.out.println("业务系统向交换平台备案公钥：" + s);
        NxYthHttpResponse response = JsonUtils.jsonStringToJavaBean(s, NxYthHttpResponse.class);
        response.setSelfPblKey(map.get(SM2Utils.PUBLIC_KEY).toString());
        response.setSelfPrtKey(map.get(SM2Utils.PRIVATE_KEY).toString());
        return response;
    }

    /**
     * 业务系统查询交换平台的SM2公钥
     */
    public static NxYthHttpResponse queryExchPubKey(SssfmNxYthServer sssfmNxYthServer) {
        Map headers = getHeader(sssfmNxYthServer, false);
        StringBuilder postJson = new StringBuilder();
        postJson.append("{}");
        String s = NXHttpUtil.doPost(sssfmNxYthServer.getUrl(), headers, postJson.toString(), sssfmNxYthServer.getUrlTimeout());
        System.out.println("业务系统查询交换平台的SM2公钥响应：" + s);
        NxYthHttpResponse response = JsonUtils.jsonStringToJavaBean(s, NxYthHttpResponse.class);
        response.setOpsPblKey(response.getDataStr());
        System.out.println(response.toString());
        return response;
    }

    /**
     * 业务系统长期密钥申请
     */
    public static NxYthHttpResponse applyLongTermKey(SssfmNxYthServer sssfmNxYthServer) throws Exception{
        // 交换平台公钥加密32位随机串
        String r = UUID.randomUUID().toString().replaceAll("-", "");
        String R = SM2Utils.encrypt(Util.hexToByte(sssfmNxYthServer.getOpsPblKey()),
                r.getBytes());
        StringBuilder postJsonApply = new StringBuilder();
        postJsonApply.append("{\"R\":\"");
        postJsonApply.append(R);
        postJsonApply.append("\"}");
        Map headers = getHeader(sssfmNxYthServer, false);
        String s = NXHttpUtil.doPost(sssfmNxYthServer.getUrl(), headers, postJsonApply.toString(), sssfmNxYthServer.getUrlTimeout());
        System.out.println("业务系统长期密钥申请：" + s);
        NxYthHttpResponse response = JsonUtils.jsonStringToJavaBean(s, NxYthHttpResponse.class);
        String dataStr = response.getDataStr();
        // 用系统私钥解密
        String SE_ret_dataStr = null;
        try {
            SE_ret_dataStr = new String(SM2Utils.decrypt(
                    Util.hexToByte(sssfmNxYthServer.getSelfPrtKey()),
                    Util.hexToByte(dataStr)
            ));
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 解析解密后的响应，分离 r、k、ack
        String SE_ret_r = SE_ret_dataStr.substring(0, 32);
        String SE_ret_k = SE_ret_dataStr.substring(32, 64);
        String SE_ret_ack = SE_ret_dataStr.substring(64, 96);
        // 业务系统校验r
        if (!r.equals(SE_ret_r)) {
            StringBuilder msg = new StringBuilder();
            msg.append("业务系统原始r=");
            msg.append(r);
            msg.append("；交换平台响应r=");
            msg.append(SE_ret_r);
            System.out.println("交换平台响应的r与系统生成值不一致：" + msg.toString());
        }
        System.out.println("长期密钥（用业务系统私钥解密）：" + SE_ret_k);
        response.setLongKeyR(SE_ret_r);
        response.setLongKey(SE_ret_k);
        response.setLongKeyAck(SE_ret_ack);
        return response;
    }
    /**
     * 业务系统长期密钥申请
     */
    public static NxYthHttpResponse confirmLongTermKey(SssfmNxYthServer sssfmNxYthServer) throws Exception{
        // 发起确认key请求
        System.out.println("1111111111111111111111111111111111");
        System.out.println(sssfmNxYthServer.toString());
        System.out.println(sssfmNxYthServer);
        System.out.println(sssfmNxYthServer.getOpsPblKey());
        Map headers = getHeader(sssfmNxYthServer, false);
        String ack_exchPubKey = SM2Utils.encrypt(
                Util.hexToByte(sssfmNxYthServer.getOpsPblKey()),
                sssfmNxYthServer.getLongKeyAck().getBytes());
        StringBuilder postJsonConfirm = new StringBuilder();
        postJsonConfirm.append("{\"ack\":\"");
        postJsonConfirm.append(ack_exchPubKey);
        postJsonConfirm.append("\"}");
        String ackResp = NXHttpUtil.doPost(sssfmNxYthServer.getUrl(), headers, postJsonConfirm.toString(), sssfmNxYthServer.getUrlTimeout());
        System.out.println("业务系统长期密钥确认：" + ackResp);
        NxYthHttpResponse ackResponse = JsonUtils.jsonStringToJavaBean(ackResp, NxYthHttpResponse.class);
//        System.out.println("交换平台响应（确认）：" + ackResponse);
        return ackResponse;
    }

    /**
     * 临时密钥申请
     */
    public static NxYthHttpResponse applyTempKey(SssfmNxYthServer sssfmNxYthServer) throws Exception{
        Map headers = getHeader(sssfmNxYthServer, true);
        // request body：json
        StringBuilder postJsonApply = new StringBuilder();
        postJsonApply.append("{}");
        String SE_retmsg = NXHttpUtil.doPost(sssfmNxYthServer.getUrl(), headers, postJsonApply.toString(), sssfmNxYthServer.getUrlTimeout());
        // 解析响应json
        System.out.println("临时密钥（用业务系统长期密钥解密前）：" + SE_retmsg);
        // 解析响应json
        NxYthHttpResponse tempKeyResp = JsonUtils.jsonStringToJavaBean(SE_retmsg, NxYthHttpResponse.class);
        String encrptedTempKey = tempKeyResp.getData().getKey();
        String token = tempKeyResp.getData().getToken();
        // 用系统长期密钥解密
        String tempKey = TranSM4Utils.decryptData_CBC(
                encrptedTempKey,
                sssfmNxYthServer.getLongKey().substring(0, 16),
                sssfmNxYthServer.getLongKey().substring(16)
        );
//        SM4Utils sm4Utils = new SM4Utils();
//        sm4Utils.secretKey=sssfmNxYthServer.getLongKey();
//        System.out.println("长秘钥："+sssfmNxYthServer.getLongKey());
//        String tempKey = sm4Utils.decryptData_CBC(encrptedTempKey);

        tempKeyResp.getData().setKey(tempKey);
        System.out.println("token：" + token);
        System.out.println("临时密钥（用业务系统长期密钥解密后）：" + tempKey);
        return tempKeyResp;
    }

    public static Map  getHeader(SssfmNxYthServer sssfmNxYthServer,Boolean isTarget){
        Map<String, String> headers = new HashMap<String, String>();
        headers.put("SE_sysCode", sssfmNxYthServer.getSeSyscode());
        headers.put("SE_userId", sssfmNxYthServer.getSeUserid());
        headers.put("SE_password", sssfmNxYthServer.getSePassword());
        if(isTarget){
            headers.put("SE_targetSysCode", sssfmNxYthServer.getSeTargetsyscode());
            headers.put("SE_targetServiceCode", sssfmNxYthServer.getSeTargetservicecode());
        }
        return headers;
    }

    public static void main(String[] args) {
        String s = UUID.randomUUID().toString().replaceAll("-", "");
        System.out.println(s.length());
        System.out.println(s.substring(0,16));
        System.out.println(s.substring(16));

    }
    @PostConstruct
    public void init(){
        List<SssfmNxYthServer> allData = sssfmNxYthServerDao.getAllData();
        for(SssfmNxYthServer server:allData){
            services.put(server.getDistCode()+"_"+server.getUrlMethod(),server);
        }
    }
    public static SssfmNxYthServer getServerByDisCodeAndMethod(String distCode,String urlMethod ){
        return services.get(distCode+"_"+urlMethod);
    }

}
